package cn.wjssl.trigger.listener;

import cn.wjssl.domain.activity.model.entity.DeliveryOrderEntity;
import cn.wjssl.domain.activity.service.IRaffleActivityAccountQuotaService;
import cn.wjssl.domain.credit.event.CreditAdjustSuccessMessageEvent;
import cn.wjssl.types.enums.ResponseCode;
import cn.wjssl.types.event.BaseEvent;
import cn.wjssl.types.exception.AppException;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author：lxd
 * @Description 积分调额成功监听器
 * @Date：2025/3/10
 */

@Slf4j
@Component
public class CreditAdjustSuccessCustomer {

    @Resource
    private IRaffleActivityAccountQuotaService accountQuotaService;

    @Value("${spring.rabbitmq.topic.credit_adjust_success}")
    private String topic;

    @RabbitListener(queuesToDeclare = @Queue(value = "${spring.rabbitmq.topic.credit_adjust_success}"))
    public void listener(String message) {
        try {
            // 1. 转换消息体
            BaseEvent.EventMessage<CreditAdjustSuccessMessageEvent.CreditAdjustSuccessMessage> sendMsg = JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<CreditAdjustSuccessMessageEvent.CreditAdjustSuccessMessage>>() {
            }.getType());
            CreditAdjustSuccessMessageEvent.CreditAdjustSuccessMessage data = sendMsg.getData();
            String outBusinessNo = data.getOutBusinessNo();
            String userId = data.getUserId();

            // 2. 根据userId, outBusinessNo, 更新sku单记录 pay_wait 为 completed
            DeliveryOrderEntity deliveryOrderEntity = DeliveryOrderEntity.builder()
                    .userId(userId)
                    .outBusinessNo(outBusinessNo)
                    .build();
            accountQuotaService.updateOrder(deliveryOrderEntity);

        } catch (AppException e) {
            if (ResponseCode.INDEX_DUP.getCode().equals(e.getCode())) {
                log.warn("监听积分账户调整成功消息，进行交易商品发货，消费重复 topic: {} message: {}", topic, message, e);
                return;
            }
            throw e;
        } catch (Exception e) {
            log.error("监听积分账户调整成功消息，进行交易商品发货失败 topic: {} message: {}", topic, message, e);
            throw e;
        }
    }
}
